package com.jky.trial.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jky.trial.common.BaseResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/map")
public class MapController {


    @GetMapping("/distance/{start}/{end}")
    public BaseResult get(
            @PathVariable String start,
            @PathVariable String end,
            HttpServletResponse response) {
        return new BaseResult(true, getDistance(start, end));
    }


    /**
     * 0.得到两个地址间距离
     */
    public static long getDistanceByAdress(String start, String end) {
        String startLonLat = getLonLat(start);
        String endLonLat = getLonLat(end);
        long dis = getDistance(startLonLat, endLonLat);
        return dis;
    }

    /**
     * 1.地址转换为经纬度
     */
    public static Map getAddressByLonLat(String latlng) {
//        String queryUrl = "https://restapi.amap.com/v3/geocode/regeo?key=82d9f8bc24cd956fdf3f1b406a59acd9&poitype=商务写字楼&radius=1000&extensions=all&batch=false&roadlevel=0&parameters" + latlng;
        String queryUrl = "http://restapi.amap.com/v3/geocode/regeo?key=82d9f8bc24cd956fdf3f1b406a59acd9&location="+latlng+"&poitype=商务写字楼&radius=1000&extensions=all&batch=false&roadlevel=0";
        String queryResult = getResponse(queryUrl);  //高德接品返回的是JSON格式的字符串
        JSONObject job = JSONObject.parseObject(queryResult);
        JSONObject jobJSON = JSONObject.parseObject(job.getString("regeocode"));
        Map map = new HashMap();
        map.put("address",jobJSON.getString("formatted_address"));
        JSONObject detail = JSONObject.parseObject(jobJSON.getString("addressComponent"));
        map.put("c",detail.getString("country"));
        map.put("p",detail.getString("province"));
        if(detail.getString("city").indexOf("[")>-1){
            map.put("c1",detail.getString("province"));
        }else{
            map.put("c1",detail.getString("city"));
        }
        return map;

    }
    private static String getLonLat(String address) {
        //返回输入地址address的经纬度信息, 格式是 经度,纬度
        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=82d9f8bc24cd956fdf3f1b406a59acd9&address=" + address;
        String queryResult = getResponse(queryUrl);  //高德接品返回的是JSON格式的字符串
        JSONObject job = JSONObject.parseObject(queryResult);
        JSONObject jobJSON = JSONObject.parseObject(job.get("geocodes").toString().substring(1, job.get("geocodes").toString().length() - 1));
        String DZ = jobJSON.get("location").toString();
        System.out.println("经纬度：" + DZ);
        return DZ;
    }


    /**
     * 2.经纬度算出两点间距离
     */
    private static long getDistance(String startLonLat, String endLonLat) {
        //返回起始地startAddr与目的地endAddr之间的距离，单位：米
        if(startLonLat=="undefined"||endLonLat=="undefined") return 0;
        Long result = new Long(0);
        String queryUrl = "http://restapi.amap.com/v3/distance?key=82d9f8bc24cd956fdf3f1b406a59acd9&origins=" + startLonLat + "&destination=" + endLonLat;
        String queryResult = getResponse(queryUrl);
        JSONObject job = JSONObject.parseObject(queryResult);
        JSONArray ja = job.getJSONArray("results");
        if(ja!=null){
        JSONObject jobO = JSONObject.parseObject(ja.getString(0));
        result = Long.parseLong(jobO.get("distance").toString());
        System.out.println("距离2：" + result);
        return result;
        }else{
            return 0;
        }
    }

    /**
     * 3.发送请求
     */
    private static String getResponse(String serverUrl) {
        //用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

}
